package com.yjt.common.utils;

import com.yjt.common.entity.TreeNode;
import io.micrometer.core.instrument.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 曾智平
 * @ClassName: TreeUtil
 * @Description: 树结构工具类
 * @date 2021/10/8 16:56
 */
public class TreeUtil {

    /**
     * 循环根结构
     *
     * @param dataList
     * @param <T>
     * @return
     */
    public static <T extends TreeNode> List<T> loopRoot(List<T> dataList) {
        List<T> treeList = new ArrayList();
        for (T treeNode : dataList) {
            if (StringUtils.isBlank(treeNode.getParentId())) {
                treeList.add(loopChildren(dataList, treeNode));
            }
        }
        return treeList;
    }

    /**
     * 循环子结构
     *
     * @param dataList
     * @param treeNode
     * @param <T>
     * @return
     */
    private static <T extends TreeNode> T loopChildren(List<T> dataList, T treeNode) {
        String rootId = treeNode.getId();
        for (T children : dataList) {
            String childrenFatherId = children.getParentId();
            if (rootId.equals(childrenFatherId)) {
                treeNode.add(loopChildren(dataList, children));
            }
        }
        return treeNode;
    }

}


